<template>
  <div class="generated-page-container">
    <div class="page-header">
      <el-button type="primary" size="small" @click="goBack">
        <i class="el-icon-arrow-left"></i>
        返回设计器
      </el-button>
      <div class="page-info">
        <h2 class="page-title">{{ pageData.pageName || "生成的页面" }}</h2>
        <p class="page-description" v-if="pageData.description">
          {{ pageData.description }}
        </p>
        <p class="page-meta">创建时间：{{ pageData.createTime }}</p>
      </div>
      <el-button type="success" size="small" @click="submitForm">
        提交表单
      </el-button>
    </div>

    <div class="page-content">
      <div v-if="loading" class="loading-container">
        <i class="el-icon-loading"></i>
        <p>正在加载页面...</p>
      </div>

      <div v-else-if="error" class="error-container">
        <i class="el-icon-warning"></i>
        <p>{{ error }}</p>
        <el-button type="primary" @click="goBack">返回设计器</el-button>
      </div>

      <div v-else class="form-container">
        <v-form-render
          ref="vFormRender"
          :form-json="pageData.formJson"
          :form-data="formData"
          :option-data="optionData"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "GeneratedPage",
  data() {
    return {
      pageData: {},
      formData: {},
      optionData: {},
      loading: true,
      error: null,
    };
  },
  mounted() {
    this.loadPageData();
  },
  methods: {
    // 从URL参数加载页面数据
    loadPageData() {
      try {
        const urlParams = new URLSearchParams(window.location.search);
        const routeName = urlParams.get("page");

        if (!routeName) {
          this.error = "未找到页面路由参数";
          this.loading = false;
          return;
        }

        // 从localStorage加载页面数据
        const pageJson = localStorage.getItem(`vform-page-${routeName}`);

        if (!pageJson) {
          this.error = `未找到路由为"${routeName}"的页面数据`;
          this.loading = false;
          return;
        }

        this.pageData = JSON.parse(pageJson);

        if (!this.pageData || !this.pageData.formJson) {
          this.error = "页面数据格式错误";
          this.loading = false;
          return;
        }

        this.loading = false;
      } catch (error) {
        this.error = "加载页面失败：" + error.message;
        this.loading = false;
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.vFormRender
        .getFormData()
        .then((formData) => {
          console.log("表单数据:", formData);

          // 显示表单数据
          this.$alert(
            `<pre style="max-height: 400px; overflow: auto; text-align: left">${JSON.stringify(
              formData,
              null,
              2
            )}</pre>`,
            "表单提交成功",
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: "确定",
            }
          );

          // 这里可以添加实际的提交逻辑
          // 比如发送到服务器
          this.submitToServer(formData);
        })
        .catch((error) => {
          console.error("表单验证失败:", error);
          this.$message.error("表单验证失败，请检查必填项");
        });
    },

    // 提交到服务器（示例）
    submitToServer(formData) {
      // 这里可以添加实际的API调用
      console.log("提交到服务器:", {
        pageId: this.pageData.id,
        routeName: this.pageData.routeName,
        formData: formData,
        submitTime: new Date().toISOString(),
      });

      // 模拟API调用
      setTimeout(() => {
        this.$message.success("数据提交成功！");
      }, 1000);
    },

    // 返回设计器
    goBack() {
      // 移除URL中的page参数，返回设计器页面
      const currentUrl = window.location.href;
      const baseUrl = currentUrl.split("?")[0];
      window.location.href = baseUrl;
    },
  },
};
</script>

<style scoped>
.generated-page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.page-header {
  background: #fff;
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-info {
  flex: 1;
  margin: 0 20px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-description {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}

.page-meta {
  margin: 0;
  color: #909399;
  font-size: 12px;
}

.page-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
}

.loading-container i {
  font-size: 32px;
  margin-bottom: 16px;
  animation: rotating 2s linear infinite;
}

.error-container i {
  font-size: 32px;
  margin-bottom: 16px;
  color: #f56c6c;
}

.loading-container p,
.error-container p {
  margin-bottom: 16px;
  font-size: 14px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 15px;
  }

  .page-info {
    margin: 15px 0;
  }

  .page-title {
    font-size: 20px;
  }

  .form-container {
    margin: 0;
    padding: 20px;
    border-radius: 0;
  }
}
</style>
